package utils

import (
	"context"
	"seat-service/initialization"
	"seat-service/model/dto"
)

const (
	Building      = "building"
	BuildingData  = "building-data"
	BuildingId    = "building-id"
	Classroom     = "classroom"
	ClassroomData = "classroom-data"
	ClassroomId   = "classroom-id"
)

// CacheRedisData 更新操作
func CacheRedisData(key string, value map[string]string) error {
	err := initialization.Redis.HSet(context.Background(), key+"-data", value).Err()
	if err != nil {
		return err
	}
	return nil
}

// CacheRedisID 更新操作
func CacheRedisID(key string, value map[string]string) error {
	err := initialization.Redis.HSet(context.Background(), key+"-id", value).Err()
	if err != nil {
		return err
	}
	return nil
}

// DeleteMapKey 删除操作 批量删除map集合中指定的元素
func DeleteMapKey(key string, fieldsToDelete []string) error {
	_, err := initialization.Redis.HDel(context.Background(), key, fieldsToDelete...).Result()
	return err
}

func CacheRedisRead() ([]dto.CacheRedisCampus, error) {
	campusStruct := make([]dto.CacheRedisCampus, 0)
	campus, err := initialization.Redis.HGetAll(context.Background(), "campus-data").Result()
	if err != nil {
		return nil, err
	}
	buildingData, err := initialization.Redis.HGetAll(context.Background(), "building-data").Result()
	if err != nil {
		return nil, err
	}
	classroomData, err := initialization.Redis.HGetAll(context.Background(), "classroom-data").Result()
	if err != nil {
		return nil, err
	}
	buildingId, err := initialization.Redis.HGetAll(context.Background(), "building-id").Result()
	if err != nil {
		return nil, err
	}
	classroomId, err := initialization.Redis.HGetAll(context.Background(), "classroom-id").Result()
	if err != nil {
		return nil, err
	}

	for i, v := range campus {
		campusStruct = append(campusStruct, dto.CacheRedisCampus{
			Id:         i,
			CampusName: v,
			Building:   make([]dto.CacheRedisBuilding, 0),
		})
	}

	for k, v := range buildingId {
		for i, v2 := range campusStruct {
			if v == v2.Id {
				campusStruct[i].Building = append(campusStruct[i].Building, dto.CacheRedisBuilding{
					Id:        k,
					Name:      buildingData[k],
					Classroom: make([]dto.CacheRedisClassroom, 0),
				})
			}
		}
	}

	for k, v := range classroomId {
		for i2, _ := range campusStruct {
			for i3, v3 := range campusStruct[i2].Building {
				if v == v3.Id {
					campusStruct[i2].Building[i3].Classroom = append(campusStruct[i2].Building[i3].Classroom, dto.CacheRedisClassroom{
						Id:       k,
						Location: classroomData[k],
					})
				}
			}
		}
	}
	return campusStruct, nil
}
